<?php

namespace app\wework\controller;

use app\BaseController;
use app\common\model\app\AppWx;
use app\common\model\app\AppWxwork;
use app\Request;
use think\facade\Cache;
use app\wework\lib\src\WXBizMsgCrypt;
use app\wework\lib\utils\HttpUtils;
use app\wework\lib\api\CorpAPI;
use app\common\service\qrcode\Base;
use app\common\model\user\User;

/**
 * 页面控制器
 */
class Index extends BaseController
{

    // 默认appid
    protected $default_app_id = 10001;
    // appid
    protected $wx_app_id;

	public function index(request $request)
    {
        $getparams = $request->param();
        $postData = $request->getContent();
        $this->responseWE($getparams,$postData);
    }

    private function appinit(){
        $wxrs = AppWx::getAppWxCache($this->default_app_id);
        $this->wx_app_id = $wxrs?$wxrs['wxapp_id']:'';
    }

    private function responseWE($params,$postData){

        // 假设企业号在公众平台上设置的参数如下
        $encodingAesKey = config('wework.encodingAesKey');
        $token = config('wework.token');
        $corpId = config('wework.corpId');

        log_write($params,'wework');
        log_write($postData,'wework');

//        $encodingAesKey = "jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C";
//        $token = "QDG6eK";
//        $corpId = "wx5823bf96d3bd56c7";

        /*
        ------------使用示例一：验证回调URL---------------
        *企业开启回调模式时，企业号会向验证url发送一个get请求
        假设点击验证时，企业收到类似请求：
        * GET /cgi-bin/wxpush?msg_signature=5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3&timestamp=1409659589&nonce=263014780&echostr=P9nAzCzyDtyTWESHep1vC5X9xho%2FqYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp%2B4RPcs8TgAE7OaBO%2BFZXvnaqQ%3D%3D
        * HTTP/1.1 Host: qy.weixin.qq.com

        接收到该请求时，企业应
        1.解析出Get请求的参数，包括消息体签名(msg_signature)，时间戳(timestamp)，随机数字串(nonce)以及公众平台推送过来的随机加密字符串(echostr),
        这一步注意作URL解码。
        2.验证消息体签名的正确性
        3. 解密出echostr原文，将原文当作Get请求的response，返回给公众平台
        第2，3步可以用公众平台提供的库函数VerifyURL来实现。

        */
        $sVerifyMsgSig = $params['msg_signature']??'';
//        $sVerifyMsgSig = "5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3";
        $sVerifyTimeStamp = $params['timestamp']??'';
//        $sVerifyTimeStamp = "1409659589";
        $sVerifyNonce = $params['nonce']??'';
//        $sVerifyNonce = "263014780";
        $sVerifyEchoStr = $params['echostr']??'';
//        $sVerifyEchoStr = "P9nAzCzyDtyTWESHep1vC5X9xho/qYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp+4RPcs8TgAE7OaBO+FZXvnaqQ==";

//        $sReqData = $this->request->param(is_null($key) ? '' : $key . '/a');
        $sReqData = $postData??'';
//        $sReqData = "<xml><ToUserName><![CDATA[wx5823bf96d3bd56c7]]></ToUserName><Encrypt><![CDATA[RypEvHKD8QQKFhvQ6QleEB4J58tiPdvo+rtK1I9qca6aM/wvqnLSV5zEPeusUiX5L5X/0lWfrf0QADHHhGd3QczcdCUpj911L3vg3W/sYYvuJTs3TUUkSUXxaccAS0qhxchrRYt66wiSpGLYL42aM6A8dTT+6k4aSknmPj48kzJs8qLjvd4Xgpue06DOdnLxAUHzM6+kDZ+HMZfJYuR+LtwGc2hgf5gsijff0ekUNXZiqATP7PF5mZxZ3Izoun1s4zG4LUMnvw2r+KqCKIw+3IQH03v+BCA9nMELNqbSf6tiWSrXJB3LAVGUcallcrw8V2t9EL4EhzJWrQUax5wLVMNS0+rUPA3k22Ncx4XXZS9o0MBH27Bo6BpNelZpS+/uh9KsNlY6bHCmJU9p8g7m3fVKn28H3KDYA5Pl/T8Z1ptDAVe0lXdQ2YoyyH2uyPIGHBZZIs2pDBS8R07+qN+E7Q==]]></Encrypt><AgentID><![CDATA[218]]></AgentID></xml>";

        $wxcpt = new WXBizMsgCrypt($token, $encodingAesKey, $corpId);
        if($sVerifyEchoStr){
            // 需要返回的明文
            $sEchoStr = "";
            $errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);
            if ($errCode == 0) {
                //日志
                log_write($sEchoStr,'wework');
//                var_dump($sEchoStr);
                // 验证URL成功，将sEchoStr返回
                echo $sEchoStr;
            } else {
                print("ERR: " . $errCode . "\n\n");
            }
        }elseif($sReqData){
            $sMsg = "";  // 解析之后的明文
            $errCode = $wxcpt->DecryptMsg($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sReqData, $sMsg);
            if ($errCode == 0) {
                $AgentID = $postData['AgentID']??'1000012';
                // 解密成功，sMsg即为xml格式的明文
//                var_dump($sMsg);
                // TODO: 对明文的处理
                $data = $this->fromXml($sMsg);
                //回调日志
                log_write($data,'wework');
//                dump($data);exit;
                // 添加外部联系人事件
                if($data['MsgType']=='event'&&($data['ChangeType']=='add_external_contact'||$data['ChangeType']=='add_half_external_contact')){
                    // 初始化
                    $this->appinit();
                    //
                    $FromUserID = $data['UserID']??'';
                    $WelcomeCode = $data['WelcomeCode']??'welcome_code_a';
                    // 查询推广员数据
                    $Wxrs = AppWxwork::getAppWxUser($FromUserID,$AgentID);

                    if($Wxrs){
                        $GoUid = $Wxrs['userid'];
                        $miniTitle = $Wxrs['title'];
                        $WelcomeStr = $Wxrs['content'];
                        // 生成推广链接
                        $appId = $this->default_app_id;
                        $linkurl = "pages/index/index?scene=uid:".$GoUid;
                        $response = Base::createShortLink($appId, $linkurl);
                        if ($response['errcode']===0) {
                            $ShortLink = $response['link']??'';
                            //实例化
                            $Capi = new CorpAPI(config('wework.corpId'), config('wework.corpsecret'));
                            // 上传二维码图片-用redis缓存三天，过期则从新上传
                            $miniImg = $this->GetWxworkImg($Capi,$AgentID);
//                            $miniImg = "3OvvTvaqLzVRCfcNmb0x2JLB7AA6przuecw9DodnObX4g9QKpzZhv6-p7CmaPXaXv";
                            // 发送个性化欢迎语
                            $wcstr = $this->buildwelcomestr($WelcomeCode,$WelcomeStr,$ShortLink,true,$linkurl,$miniImg,$miniTitle);
                            //“发送”日志
                            log_write("UID:".$FromUserID."==>".$wcstr,'wework');
                            $resp = $Capi->WelComeMessageSend($wcstr);
                            //“完成”日志
                            log_write($resp,'wework');

                            dump("response");
                            dump($resp);
                            exit;
                        }
                        dump("OUT");
                        dump($response);
                        exit;
                    }
                }
                echo "";
                /*
                "<xml><ToUserName><![CDATA[wx5823bf96d3bd56c7]]></ToUserName>
                <FromUserName><![CDATA[mycreate]]></FromUserName>
                <CreateTime>1409659813</CreateTime>
                <MsgType><![CDATA[text]]></MsgType>
                <Content><![CDATA[hello]]></Content>
                <MsgId>4561255354251345929</MsgId>
                <AgentID>218</AgentID>
                </xml>"
                */
            } else {
                print("ERR: " . $errCode . "\n\n");
                //exit(-1);
            }
        }
    }

    public function getuserlist(){
        $Capi = new CorpAPI(config('wework.corpId'), config('wework.corpsecret'));

        $departmentId = 22;
        $response = $Capi->UserSimpleList($departmentId,1);
        dump("OUT");
        dump($response);
        exit;
    }

    private function buildwelcomestr($welcome_code,$WelcomeStr='',$ShortLink='',$minip=false,$minipage='pages/index/index',$miniImg='',$miniTitle='酒秒达送酒快，喝酒无需再等待'){
        $str = (object)array();
        $str->welcome_code = $welcome_code;
        $str->text = (object)array();
        if($WelcomeStr){
            $NoPStr = str_replace("\\n",PHP_EOL,$WelcomeStr);
            $str->text->content = $NoPStr;
        }else{
            $str->text->content = '❤HI，感谢您关注酒秒达，很高兴接下来为您服务☀。'.PHP_EOL.PHP_EOL.'🎁首单领券立减 周周低价买酒！'.PHP_EOL.'😘更多福利记得关注酒秒达商城哟👇';
        }
        if($ShortLink){
            $str->text->content .= PHP_EOL.$ShortLink;
        }
        if($minip){
            $miniprogram = (object)array();
            $miniprogram->title = $miniTitle;
            $miniprogram->pic_media_id = $miniImg;
            $miniprogram->appid = $this->wx_app_id;
            $miniprogram->page = "/".$minipage;
            $str->miniprogram = $miniprogram;
        }
//        dump(json_encode($str));exit;
        return json_encode($str);
    }

    private function fromXml($xml)
    {
        // 禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    }

    /**
     * @Exp 获取推广图片-缓存-没有就上传一个有效期三天
     * @Auth Mr.Z
     * @Date 2024/6/27
     * @param $model
     * @param $agentid
     * @return mixed|string
     */
    private function GetWxworkImg($model,$agentid='1000012'){
        $cachekey = "app_wxwork_img_".$agentid;
        $OutTime = 3600*24*3-60; //三天-防延迟提前1分钟
        if (!$MediaId = Cache::get($cachekey)) {
            $image = "./temp/10001/wxwork/1.png";
            $MediaId = $model->MediaUpload($image,'image');
            if($MediaId && is_string($MediaId)){
                Cache::set($cachekey, $MediaId, $OutTime);
                return $MediaId;
            }
            return "";
        }
        return $MediaId;
    }
}
